package com.bw.controller;

import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSONObject;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.GiteeUtils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class GiteeBindController {

    @Autowired
    UserMapper userMapper;


    @RequestMapping("/callbackCode.do")
    public String callback(String code, HttpServletRequest request, HttpServletResponse response){
        System.out.println("临时授权码 " + code);
        //根据授权码code，获得access_token
        String tokenByCode = GiteeUtils.getAccessTokenByCode(code);
        System.out.println("获取到的token " + tokenByCode);

        JSONObject userInfoByToken = GiteeUtils.getGiteeUserInfoByToken(tokenByCode);
        System.out.println("获取到的 用户信息 " + JSONObject.toJSONString(userInfoByToken));

        // 解析出3个字段
        String avatarUrl = userInfoByToken.getString("avatar_url");
        String nickName = userInfoByToken.getString("name");
        Integer gieeId = userInfoByToken.getInteger("id");

        // 进行账号的合并  （绑定）

        // 获取当前登录用户
        User userFromRequest = TokenUtils.getLoginUserFromRequest(request, User.class);

        userFromRequest.setGiteeId(gieeId);
        userFromRequest.setAvatarUrl(avatarUrl);
        userFromRequest.setNickName(nickName);
        userMapper.updateUserById(userFromRequest);

        // 重新加密用户 （用户的资料发生变化了， 需要重新制作令牌）
        TokenUtils.responseTokenByCookie(userFromRequest,response,30);


        return "redirect:list.do";

    }
}
